class AccountsController < ManageController
  before_filter:has_account,
                 :except=>[:account_edit]
  before_filter:post?,
                 :only=>[:account_update,:add_money]
  
  def has_account
      @account=Account.find_by_user_id(session[:user_id])
      unless @account
        notice("请先填写你的支付帐号！")
        redirect_to(:action=>:account_edit)
      end      
  end
  
  def post?
    unless request.post?
      notice("非正常操作！")
      redirect_to(:controller=>:manage,:action=>:error_msg)
    end
  end
  
  def account_list
    @account_records=AccountRecord.find(:all,:conditions=>["account_id=?",@account.id])
  end
  
  def account_edit
    if account=User.find(session[:user_id]).account
      @account_num=account.account_num
    else
      @account_num=""
    end
  end
  
  def account_update
    user=User.find(session[:user_id])
    if user.account.nil?
      acc=Account.new 
      acc.account_money=0      
    end
      acc.account_num=params[:account_num]
    begin 
      acc.save!
      user.account=acc
      user.save!
    rescue ActiveRecord::RecordNotSaved
      notice("绑定失败！")
      redirect_to(:action=>:account_edit)
    else
      notice("绑定成功！")
      redirect_to(:action=>:account_edit)
    end
  end
  
  def to_add_money
    acc=Account.find_by_user_id(session[:user_id])
    unless acc.nil?
      @account_num=acc.account_num
    else
      redirect_to(:action=>:account_edit)
    end
  end
  
  def add_money
      begin
        acc=User.find(session[:user_id]).account
        AccountManager.add_money({:account=>acc,:money=>params[:money]})
      rescue ActiveRecord::RecordNotSaved
        notice("充值失败！")
        redirect_to(:action=>:account_edit)
      else
        notice("充值成功！")
        redirect_to(:action=>:account_edit)
      end
  end
  
end
